<template>
	<div class="add_edit">
		<use-box>
			<el-form :model="form" label-width="120px" ref="ruleForm" :rules="rules">
				<el-form-item label="优惠券类型">
					<el-radio-group v-model="form.type" @change="typeChange">
						<el-radio label="满减">满减</el-radio>
						<el-radio label="折扣">折扣</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="订单金额" prop="order_amount" ref="order_amount">
					<el-radio-group v-model="form.no_limit" @change="amountChange">
						<div class="dflex_vertical_c no_limit">
							<el-radio label="不限制"></el-radio>
							<div class="dflex_vertical_c">
								<el-radio label="消费满" class="margin_r_10"></el-radio>
								<el-input size="mini" type="number" :min="0" v-model.number="form.order_amount"
									:disabled="form.no_limit == '不限制'" @change="priceChange" clearable></el-input>
								<div class="margin_l_10 no_limit_txt">元</div>
							</div>
						</div>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="满减金额" prop="full_reduction" ref="full_reduction" v-if="form.type == '满减'">
					<el-input type="number" :min="0" v-model.number="form.full_reduction" placeholder="请输入满减金额"
						@input="priceChange" clearable oninput="value = parseInt(value)"></el-input>
					<div class="remark_txt">单位分 {{ form.full_reduction || 0 }}分 = 减{{ form.full_reduction / 100 }}元
					</div>
				</el-form-item>
				<el-form-item label="折扣比例" prop="discount" ref="discount" v-if="form.type == '折扣'">
					<el-input type="number" :min="0" :max="99" v-model.number="form.discount" placeholder="请输入折扣比例"
						@input="priceChange" clearable oninput="value = parseInt(value)"></el-input>
					<div class="remark_txt">{{ form.discount || 0 }} = {{ form.discount / 10 }}折</div>
				</el-form-item>
				<el-form-item label="优惠券名称" prop="name" ref="name">
					<el-input v-model="form.name" placeholder="请输入名称" clearable></el-input>
				</el-form-item>
				<el-form-item label="每人限领" prop="per_max" ref="per_max">
					<el-select ref="select" v-model="form.per_max" placeholder="请选择" clearable>
						<el-option v-for="item in quotaOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="发行数量" prop="num" ref="num">
					<el-input type="number" v-model.number="form.num" placeholder="请输入数量" :min="0" clearable
						oninput="value = parseInt(value)"></el-input>
				</el-form-item>
				<el-form-item label="优惠券时间" prop="activityTime" ref="activityTime">
					<el-date-picker ref="datetimerange" v-model="form.activityTime" type="datetimerange" align="right"
						range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
						:picker-options="pickerTimeOptions" class="time"></el-date-picker>
				</el-form-item>
				<el-form-item label="描述">
					<el-input v-model="form.note" placeholder="请输入描述" clearable></el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="form.remark" placeholder="请输入备注" clearable></el-input>
				</el-form-item>
				<el-form-item label="用户类型">
					<el-radio-group v-model="form.member_type">
						<el-radio label="所有人">所有人</el-radio>
						<el-radio label="指定会员" :disabled="form.receive_type == '注册会员'">
							指定用户
							<span class="remark_txt">（通过系统赠送优惠券）</span>
						</el-radio>
						<el-radio label="付费会员">付费会员</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="领取规则">
					<el-radio-group v-model="form.receive_type">
						<el-radio label="主动发放">手动领取</el-radio>
						<el-radio :disabled="form.member_type == '指定会员'" label="注册会员">注册用户自动发放</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="使用范围" prop="allow_type" ref="allow_type">
					<el-radio-group v-model="form.allow_type" @change="allowTypeChange">
						<el-radio label="all">全场通用</el-radio>
						<el-radio label="goods">商品相关</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="form.allow_type !== 'all'">
					<el-button round class="addGoods-btn" icon="el-icon-plus" @click="addAllowType"></el-button>
				</el-form-item>
				<el-form-item v-if="form.allow_type == 'goods'">
					<div class="dflex_wrap">
						<el-card :body-style="{ padding: '0px' }" shadow="hover"
							class="card margin_b_10 padding_10 padding_t_20 pos_r margin_r_15 crpr"
							v-for="(item, i) in goods" :key="i">
							<use-carousel :width="150" :height="150" :imgs="item.imgs" :video="item.video">
							</use-carousel>
							<div class="card_bottom pos_a">
								<el-popover :open-delay="350" :close-delay="80" placement="top" trigger="hover"
									:content="item.name">
									<div slot="reference" class="name pos_a ellipsis crpr padding_lr_10 sele_none">
										{{ item.name }}
									</div>
								</el-popover>
								<div class="price pos_a sele_none">{{ item.price / 100 }}</div>
								<div class="m_price pos_a sele_none">{{ item.market_price / 100 }}</div>
							</div>
							<div class="el-icon-close crpr pos_a" @click="goodsRemove(item, i)"></div>
						</el-card>
					</div>
				</el-form-item>
				<el-form-item>
					<use-affix ref="useAffix" position="bottom" :offset="58">
						<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
							@click="submitForm('ruleForm')">提交</el-button>
						<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
					</use-affix>
				</el-form-item>
			</el-form>
		</use-box>
		<goods ref="goodsRef" @choiceGoods="getGoodsDatas"></goods>
	</div>
</template>

<script>
	const __name = 'wmzmall-marketing-coupon-rule';
	export default {
		data() {
			const validateAllowType = async (rule, value, callback) => {
				if (value == 'goods' && this.goods.length == 0) {
					return callback(new Error('请选择相关商品'));
				}

				callback();
			};
			return {
				dataId: '',
				formLoading: false,
				form: {
					type: '满减',
					no_limit: '不限制',
					order_amount: 0,
					full_reduction: '',
					discount: '',
					price: '',
					name: '',
					per_max: '',
					num: '',
					activityTime: [],
					start_time: '',
					end_time: '',
					member_type: '所有人',
					receive_type: '主动发放',
					allow_type: 'all',
					allow_ids: [],
					allow_jsons: [],
					state: '待激活',
					note: '',
					remark: '',
					receive_num: 0,
					use_num: 0
				},
				quotaOptions: [{
						value: 0,
						label: '不限张'
					},
					{
						value: 1,
						label: '1张'
					},
					{
						value: 2,
						label: '2张'
					},
					{
						value: 3,
						label: '3张'
					},
					{
						value: 4,
						label: '4张'
					},
					{
						value: 5,
						label: '5张'
					}
				],
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 3600 * 1000 * 24;
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [end, start]);
							}
						}
					]
				},
				rules: {
					name: [{
						required: true,
						message: '请输入优惠券名称',
						trigger: 'change'
					}],
					full_reduction: [{
						required: true,
						message: '请输入满减金额',
						trigger: 'change'
					}],
					discount: [{
						required: true,
						pattern: /^([0-9]{1,2}|99)$/,
						message: '返利比例只能 0~99',
						trigger: 'change'
					}],
					order_amount: [{
						required: true,
						message: '请输入满多少元可使用',
						trigger: 'change'
					}],
					num: [{
						required: true,
						message: '请输入发行数量',
						trigger: 'change'
					}],
					per_max: [{
						required: true,
						message: '请选择每人限领',
						trigger: 'change'
					}],
					activityTime: [{
						type: 'array',
						required: true,
						message: '请选择优惠券时间',
						trigger: 'change'
					}],
					allow_type: [{
						required: false,
						validator: validateAllowType,
						trigger: 'blur'
					}]
				},
				goodsIds: [],
				goods: []
			};
		},
		methods: {
			async loadData() {
				if (!this.dataId) {
					return;
				}

				await this.$db[__name].tofirst(this.dataId).then(res => {
					if (res.code == 200) {
						for (let item in this.form) {
							this.form[item] = res.datas[item];
						}

						if (res.datas.order_amount > 0) {
							this.form.no_limit = '消费满';
						} else {
							this.form.no_limit = '不限制';
						}

						this.form.full_reduction = res.datas.price;

						this.form.discount = res.datas.price;

						this.form.activityTime = [];
						this.form.activityTime.push(res.datas.start_time);
						this.form.activityTime.push(res.datas.end_time);

						if (this.form.allow_type == 'goods') {
							this.goodsIds = res.datas.allow_ids;
							this.goods = res.datas.allow_jsons;
						}
					}
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						this.form.price = this.form.full_reduction || this.form.discount;

						if (this.form.no_limit == '不限制') {
							this.form.order_amount = 0;
						}

						if (this.form.activityTime && this.form.activityTime.length) {
							this.form.start_time = new Date(this.form.activityTime[0]).getTime();
							this.form.end_time = new Date(this.form.activityTime[1]).getTime();
						}

						if (this.form.allow_type == 'goods') {
							if (this.goodsIds.length == 0) {
								this.$message({
									message: '请选择商品相关',
									type: 'warning'
								});
								return;
							}
							this.form.allow_ids = this.goodsIds;
							this.form.allow_jsons = this.goods;
						}

						delete this.form.full_reduction;
						delete this.form.discount;
						delete this.form.no_limit;
						delete this.form.activityTime;

						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			typeChange() {
				this.form.name = '';
				this.form.full_reduction = '';
				this.form.discount = '';
			},
			priceChange() {
				if (this.form.type == '满减' && this.form.full_reduction != '') {
					this.form.name = '减' + this.form.full_reduction / 100 + '元';
					if (this.form.type == '满减' && this.form.full_reduction != '' && this.form.order_amount != '') {
						this.form.name = '满' + this.form.order_amount + '减' + this.form.full_reduction / 100;
					}
				}
				if (this.form.type == '折扣' && this.form.discount != '') {
					this.form.name = this.form.discount / 100 + '折';
					if (this.form.type == '折扣' && this.form.discount != '' && this.form.order_amount != '') {
						this.form.name = '满' + this.form.order_amount + '折' + this.form.discount / 100;
					}
				}
			},
			amountChange(res) {
				if (res == '消费满') {
					this.form.order_amount = '';
				} else {
					this.form.order_amount = 0;
					if (this.form.type == '满减' && this.form.full_reduction != '') {
						this.form.name = '减' + this.form.full_reduction / 100 + '元';
					}
					if (this.form.type == '折扣' && this.form.discount != '') {
						this.form.name = this.form.discount / 100 + '折';
					}
				}
			},
			allowTypeChange(res) {
				if (res == 'all') {
					this.rules.allow_type[0].required = false;
					this.$refs.ruleForm.validateField('allow_type');
					if (this.goods.length > 0) {
						this.$confirm('此操作将清空商品！', '提示', {
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							})
							.then(() => {
								this.goodsIds = [];
								this.goods = [];
							})
							.catch(() => {
								this.form.allow_type = 'goods';
								this.rules.allow_type[0].required = true;
							});
					}
				} else {
					this.rules.allow_type[0].required = true;
				}
			},
			addAllowType() {
				if (this.form.allow_type == 'goods') {
					this.$refs.goodsRef.show({
						_id: this.$db.$cmd.nin(this.goodsIds),
						state: '销售中'
					});
				}
			},
			getGoodsDatas(datas) {
				datas.forEach(data => {
					this.goodsIds.push(data._id);
					this.goods.push(data);
				});
				this.$nextTick(() => {
					this.$refs.useAffix.getAffixScrollBox();
					this.$refs.allow_type.clearValidate();
				});
			},
			goodsRemove(item, index) {
				this.goods.splice(this.goods.indexOf(item), 1);
				this.goodsIds.splice(index, 1);
				if (this.goods.length <= 0) {
					this.$refs.ruleForm.validateField('allow_type');
				}
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/marketing/coupon/coupon'
				});
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.use-box', this.$route.path);
			});

			this.$nextTick(() => {
				this.$api.scrollToStorage('.use-box', this.$route.path);
			});

			const ele = document.querySelector('.use-box');

			this.$nextTick(() => {
				ele.addEventListener('scroll', () => {
					if (this.$refs.select.visible) {
						this.$refs.select.visible = false;
					}
					if (this.$refs.datetimerange.pickerVisible) {
						this.$refs.datetimerange.pickerVisible = false;
					}
				});
			});
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style>
	.no_limit .el-input {
		width: 35%;
		height: 28px;
	}

	.no_limit_txt {
		font-size: 14px;
		color: #606266;
		font-weight: 500;
	}

	.addGoods-btn:hover,
	.addGoods-btn:focus {
		color: #ff6a6c;
		border-color: #ff6a6c;
		background-color: #fff;
	}

	.card {
		border-radius: 10px;
		overflow: hidden;
	}

	.card .card_bottom {
		left: 0;
		right: 0;
		bottom: 0;
		color: #fff;
		width: 100%;
		height: 70px;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 999;
	}

	.card_bottom .name {
		top: 0;
		font-size: 16px;
	}

	.card_bottom .price {
		top: 20px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card_bottom .m_price {
		top: 36px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card .ellipsis {
		width: 100%;
	}

	.card .el-icon-close {
		right: 4px;
		top: 4px;
	}

	.card .el-icon-close:hover {
		color: #ff6a6c;
	}
</style>
